<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\user\XhsysUser;
use Helpers\Tool;
use Modules\Power;
use Helpers\Main;
use Helpers\Template;
use Helpers\Assets;
use Helpers\User;
use Helpers\Hrm;
use Helpers\Area;
use Modules\School;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\track\XhwebProblem;
use Admin\Models\track\XhwebProblemAnswer;


class WebproblemController extends ControllerBase
{
    private static $problemStatus = [
        1 => '待解决',
        2 => '已解决',
    ];

    /**
     * 网络问题列表
     *
     *
     * @return mixed
     * @throws \Helpers\XhException
     * @throws \Lybc\PhpGB2260\InvalidCodeException
     *
     * create by zqk 20181219
     * modify by zqk 20181229
     */
    public function indexAction()
    {
        if (!Power::exist('WebProblem')) {
            return $this->sendViewError('无网络问题权限');
        }
        Assets::easyUI('js/web_problem/webProblemList.js');
        Assets::select2();
        Assets::sweetAlert2();
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->pick('web_problem/webProblemList');
        $listSearchArr = $listButtonArr = [];
        if (Power::exist('WebProblem_Add')) {
            $listButtonArr[] = [
                'id' => 'bt_list_add',
                'text' => '新增',
                'plain' => 'true',
                'icon' => 'fa-plus',
                'style' => 'cursor: pointer;'
            ];
        }
        if (Power::exist('WebProblem_Del')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_del',
                'text' => '删除',
                'icon' => 'fa-trash',
                'style' => 'margin-left:10px'
            ];
        }
        if (Power::exist('WebProblem_Edit')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_edit',
                'text' => '编辑',
                'icon' => 'fa-edit',
                'style' => 'margin-left:10px'
            ];
        }


        //搜索
        $areaObj = new Area();
        $provArr = $areaObj->getAllProvinces(true);
        $listSearchArr[] = ['type' => 'select',
            'label' => ' ',
            'id' => 'school_province',
            'style' => 'width: 120px;',
            'data' => ['' => '--省--'] + $provArr,
        ];

        $listSearchArr[] = ['type' => 'select',
            'label' => ' ',
            'id' => 'school_city',
            'style' => 'width: 120px;',
            'data' => ['' => '--市--'],
        ];

        $listSearchArr[] = ['type' => 'select',
            'label' => ' ',
            'id' => 'school_zone',
            'style' => 'width: 120px;',
            'data' => ['' => '--区--'],
        ];
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'school_area', 'style' => 'width: 110px;'];
        $listSearchArr[] = ['type' => 'select',
            'label' => ' ',
            'id' => 'list_status',
            'style' => 'width: 120px;',
            'data' => ['' => '--状态--'] + self::$problemStatus];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => ' 搜索学校： '];
        $listSearchArr[] = [
            'type' => 'button',
            'id' => 'bt_list_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        ];
        if (Power::exist('WebProblem_Export')) {
            $listSearchArr[] = [
                'type' => 'button',
                'id' => 'bt_list_export',
                'text' => '导出',
                'icon' => 'fa-file-excel-o',
                'style' => 'margin-left:10px'
            ];
        }
        return $this->view->setVars([
            'List' => Template::createList('list', 'WebProblem_List', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by zqk 20181219
     */
    public function getWebProblemAction()
    {
        if (!Power::exist('WebProblem')) {
            return $this->sendErrorResponse(403, '无网络问题权限');
        }
        $sSchoolName = trim($this->request->getPost('sSchoolName', 'string'));
        $status = $this->request->getPost('status', 'int');
        $province = $this->request->getPost('province', 'string');
        $city = $this->request->getPost('city', 'string');
        $zone = $this->request->getPost('zone', 'string');
        $school_area = $this->request->getPost('schoolArea', 'int');
        $userId = Main::getLoginUserInfo('userId');
        $deps = User::getextrapower('dep', 'webProblem');  //获取扩展部门权限
        $schoolIds = School::getPower();                                //拥有权限的学校
        $uids = [];
        //根据扩展部门获取部门下的uid 以及部门 Tag
        if ($deps) {
            $uids = Hrm::getDepUserIdByDepId($deps);
        }
        array_push($uids, $userId);
        $uids = array_unique($uids);
        try {
            $condition = 'bDelete = 0';
            // 审核状态查询
            if ($status) {
                $condition .= " AND iStatus = $status";
            }
            // 关键字查询
            if (!empty($sSchoolName)) {
                $searchSchoolIds = School::searchSchool($sSchoolName);
                if (empty($searchSchoolIds)) {
                    $condition .= ' and sTitle like "%' . $sSchoolName . '%"';
                }
            }

            if (!empty($province) && $province != '--省--') {
                $location['province']  = $province;
                if (!empty($city) && $city != '--市--') {
                    $location['city'] = $city;
                    if (!empty($zone) && $zone != '--区--') {
                        $location['county'] = $zone;
                    }
                }
                $locationSchoolIds = School::getSchoolsByArea($location);
                $locationSchoolIds = array_keys($locationSchoolIds);
                if (empty($locationSchoolIds)) {
                    return $this->sendJsonResponse(['total'=>0, 'rows' => [] ]);
                }
            }

            if (!empty($school_area)) {
                $depId  = $school_area;
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
                $authId = $staff['iUserId'];
                if (!empty($authId)) {
                    $areaSchoolIds = User::getSchool(true, $authId, true);
                    $areaSchoolIds = array_keys($areaSchoolIds);
                }
                if (empty($areaSchoolIds)) {
                    return $this->sendJsonResponse(['total'=>0, 'rows' => [] ]);
                }
            }
            //根据部门扩展
            $uProblemIds = $this->modelsManager->createBuilder()
                ->columns("iId")
                ->addFrom('Admin\Models\track\XhwebProblem')
                ->where($condition)
                ->inWhere('iCreateUserId', $uids);
            if (!empty($searchSchoolIds)) {
                $uProblemIds ->inWhere('iSchoolId', $searchSchoolIds);
            }
            if (!empty($locationSchoolIds)) {
                $uProblemIds ->inWhere('iSchoolId', $locationSchoolIds);
            }
            if (!empty($areaSchoolIds)) {
                $uProblemIds ->inWhere('iSchoolId', $areaSchoolIds);
            }
            $uProblemIds = $uProblemIds->getQuery()->execute()->toArray();
            $uProblemIds = array_column($uProblemIds, 'iId');
            $sProblemIds = [];
            //扩展学校所属的申请
            if ($schoolIds !== true && !empty($schoolIds) && is_array($schoolIds)) {
                if (!empty($searchSchoolIds)) {
                    $schoolIds = array_intersect($schoolIds, $searchSchoolIds);
                }
                if (!empty($locationSchoolIds)) {
                    $schoolIds = array_intersect($schoolIds, $locationSchoolIds);
                }
                if (!empty($areaSchoolIds)) {
                    $schoolIds = array_intersect($schoolIds, $areaSchoolIds);
                }
                $sProblemIds = $this->modelsManager->createBuilder()
                    ->columns("iId")
                    ->addFrom('Admin\Models\track\XhwebProblem')
                    ->where($condition)
                    ->inWhere('iSchoolId', $schoolIds)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $sProblemIds = array_column($sProblemIds, 'iId');
            } elseif ($schoolIds === true) {
                $sProblemIds = $this->modelsManager->createBuilder()
                    ->columns("iId")
                    ->addFrom('Admin\Models\track\XhwebProblem')
                    ->where($condition);
                if (!empty($searchSchoolIds)) {
                    $sProblemIds ->inWhere('iSchoolId', $searchSchoolIds);
                }
                if (!empty($locationSchoolIds)) {
                    $sProblemIds ->inWhere('iSchoolId', $locationSchoolIds);
                }
                if (!empty($areaSchoolIds)) {
                    $sProblemIds ->inWhere('iSchoolId', $areaSchoolIds);
                }
                $sProblemIds = $sProblemIds->getQuery()->execute()->toArray();
                $sProblemIds = array_column($sProblemIds, 'iId');
            }
            $iIds = array_unique(array_merge($sProblemIds, $uProblemIds));
            $builder = $this->modelsManager->createBuilder()
                ->columns("iId,iSchoolId,iStudId,sTitle,sAdClsName,iStatus,tCreateDate,iCreateUserId,tLastModifyDate")
                ->addFrom('Admin\Models\track\XhwebProblem')
                ->where($condition)
                ->inWhere('iId', $iIds)
                ->orderBy('iId desc');
            $data = Main::runBuilderPages($builder, true);
            // 数据展示类型切换
            foreach ($data['rows'] as $k => $row) {
                $data['rows'][$k]['iStatusName'] = $this->getApplyStatus($row['iStatus']);
            }
            Main::runUserNameById($data['rows'], ['iCreateUserId' => 'sCreateUserName'], true);
            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
            return $this->sendJsonResponse($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 导出
     *
     *
     * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20190102
     */
    public function exportProblemDataAction()
    {
        if (!Power::exist('WebProblem_Export')) {
            return $this->sendErrorResponse(403, '无网络问题导出权限');
        }
        $this->view->disable();
        $sSchoolName = trim($this->request->getPost('sSchoolName', 'string'));
        $status = $this->request->getPost('status', 'int');
        $province = $this->request->getPost('province', 'string');
        $city = $this->request->getPost('city', 'string');
        $zone = $this->request->getPost('zone', 'string');
        $school_area = $this->request->getPost('schoolArea', 'int');
        $userId = Main::getLoginUserInfo('userId');
        $deps = User::getextrapower('dep', 'webProblem');  //获取扩展部门权限
        $schoolIds = School::getPower();                                //拥有权限的学校
        $uids = [];
        //根据扩展部门获取部门下的uid 以及部门 Tag
        if ($deps) {
            $uids = Hrm::getDepUserIdByDepId($deps);
        }
        array_push($uids, $userId);
        $uids = array_unique($uids);
        try {
            $condition = 'p.bDelete = 0';
            // 审核状态查询
            if ($status) {
                $condition .= " AND p.iStatus = $status";
            }
            // 关键字查询
            if (!empty($sSchoolName)) {
                $searchSchoolIds = School::searchSchool($sSchoolName);
                if (empty($searchSchoolIds)) {
                    $condition .= ' and p.sTitle like "%' . $sSchoolName . '%"';
                }
            }
            if (!empty($province) && $province != '--省--') {
                $location['province']  = $province;
                if (!empty($city) && $city != '--市--') {
                    $location['city'] = $city;
                    if (!empty($zone) && $zone != '--区--') {
                        $location['county'] = $zone;
                    }
                }
                $locationSchoolIds = School::getSchoolsByArea($location);
                $locationSchoolIds = array_keys($locationSchoolIds);
                if (empty($locationSchoolIds)) {
                    return $this->sendJsonResponse(['total'=>0, 'rows' => [] ]);
                }
            }
            if (!empty($school_area)) {
                $depId  = $school_area;
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
                $authId = $staff['iUserId'];
                if (!empty($authId)) {
                    $areaSchoolIds = User::getSchool(true, $authId, true);
                    $areaSchoolIds = array_keys($areaSchoolIds);
                }
                if (empty($areaSchoolIds)) {
                    return $this->sendJsonResponse(['total'=>0, 'rows' => [] ]);
                }
            }
            //根据部门扩展
            $uProblemIds = $this->modelsManager->createBuilder()
                ->columns("p.iId")
                ->addFrom('Admin\Models\track\XhwebProblem', 'p')
                ->where($condition)
                ->inWhere('p.iCreateUserId', $uids);
            if (!empty($searchSchoolIds)) {
                $uProblemIds ->inWhere('p.iSchoolId', $searchSchoolIds);
            }
            if (!empty($locationSchoolIds)) {
                $uProblemIds ->inWhere('p.iSchoolId', $locationSchoolIds);
            }
            if (!empty($areaSchoolIds)) {
                $uProblemIds ->inWhere('p.iSchoolId', $areaSchoolIds);
            }
            $uProblemIds = $uProblemIds->getQuery()->execute()->toArray();
            $uProblemIds = array_column($uProblemIds, 'iId');
            $sProblemIds = [];
            //扩展学校所属的申请
            if ($schoolIds !== true && !empty($schoolIds) && is_array($schoolIds)) {
                if (!empty($searchSchoolIds)) {
                    $schoolIds = array_intersect($schoolIds, $searchSchoolIds);
                }
                if (!empty($locationSchoolIds)) {
                    $schoolIds = array_intersect($schoolIds, $locationSchoolIds);
                }
                if (!empty($areaSchoolIds)) {
                    $schoolIds = array_intersect($schoolIds, $areaSchoolIds);
                }
                $sProblemIds = $this->modelsManager->createBuilder()
                    ->columns("p.iId")
                    ->addFrom('Admin\Models\track\XhwebProblem', 'p')
                    ->where($condition)
                    ->inWhere('p.iSchoolId', $schoolIds)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $sProblemIds = array_column($sProblemIds, 'iId');
            } elseif ($schoolIds === true) {
                $sProblemIds = $this->modelsManager->createBuilder()
                    ->columns("p.iId")
                    ->addFrom('Admin\Models\track\XhwebProblem', 'p')
                    ->where($condition);
                if (!empty($searchSchoolIds)) {
                    $sProblemIds ->inWhere('p.iSchoolId', $searchSchoolIds);
                }
                if (!empty($locationSchoolIds)) {
                    $sProblemIds ->inWhere('p.iSchoolId', $locationSchoolIds);
                }
                if (!empty($areaSchoolIds)) {
                    $sProblemIds ->inWhere('p.iSchoolId', $areaSchoolIds);
                }
                $sProblemIds = $sProblemIds->getQuery()->execute()->toArray();
                $sProblemIds = array_column($sProblemIds, 'iId');
            }
            $iIds = array_unique(array_merge($sProblemIds, $uProblemIds));
            $data = $this->modelsManager->createBuilder()
                ->columns("p.iId,p.iSchoolId,p.iStudId,p.sTitle,p.sAdClsName,p.sContent,p.iStatus,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,a.sContent as sAnswerContent")
                ->addFrom('Admin\Models\track\XhwebProblem', 'p')
                ->leftjoin('Admin\Models\track\XhwebProblemAnswer', 'p.iId = a.iProblemId and a.bBest = 1 and a.bDelete = 0', 'a')
                ->where($condition)
                ->inWhere('p.iId', $iIds)
                ->orderBy('p.iId desc')
                ->getQuery()
                ->execute()
                ->toArray();
            // 数据展示类型切换
            foreach ($data as $k => $row) {
                $data[$k]['iStatusName'] = self::$problemStatus[$data[$k]['iStatus']];
            }
            Main::runUserNameById($data, ['iCreateUserId' => 'sCreateUserName'], true);
            Main::runSchoolNameByIdStr($data, ['iSchoolId' => 'sSchoolName']);
            $title = [
                'sTitle' => '问题名称',
                'iStatusName' => '问题状态',
                'sAnswerContent' => '最佳答案',
                'sContent' => '问题内容',
                'sSchoolName' => '所属学校',
                'sAdClsName' => '所属班级',
                'sCreateUserName' => '创建人',
                'tCreateDate' => '创建时间',
            ];
            $datas = [];
            foreach ($data as $v) {
                $row = [];
                foreach ($title as $filed => $name) {
                    $row[$filed] = Tool::getValue($v, $filed);
                }
                $datas[] = $row;
            }
            $fileName = '网络问题记录';
            Tool::exportExcelOnline($fileName, $title, $datas, 'xlsx', ['header' => ['title' => '网络问题记录', 'width' => '300']]);
            return true;
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }




    /**
     * 获取申请状态的样式
     *
     * @param $status
     *
     * @return mixed
     *
     * create by zqk 20180927
     */
    private function getApplyStatus($status)
    {
        $final_Status = [
            1 => '<div class="grid-cell-text-bg-gray" style="display: inherit">待解决</div>',
            2 => '<div class="grid-cell-text-bg-green" style="display: inherit">已解决</div>',
        ];
        return $final_Status[$status];
    }

    /**
     * 新建/编辑问题跟踪Form表单
     *
     *
     * @return mixed
     * @throws \Helpers\XhException
     *
     * create by zqk 20181219
     */
    public function webProblemFormAction()
    {
        $iId = $this->request->getQuery('iId');
        $webProblem = [];
        if ($iId) {
            if (!Power::exist('WebProblem_Edit')) {
                return $this->sendViewError('无网络问题编辑权限');
            }
            $webProblem = XhwebProblem::findFirst([
                'conditions' => 'bDelete = 0 And iId = ' . $iId
            ]);
            if (empty($webProblem)) {
                return $this->sendViewError('该申请不存在');
            } else {
                $webProblem = $webProblem->toArray();
            }
        } else {
            if (!Power::exist('WebProblem_Add')) {
                return $this->sendViewError('无网络问题新增权限');
            }
        }
        Assets::select2();
        Assets::UEditor();
        Assets::easyUI('js/web_problem/addWebProblem.js');
        Assets::importMainJs('assets/jquery/jquery.form.js');
        $schoolIds = School::getPower();
        if (is_array($schoolIds)) {
            $schools = $this->modelsManager->createBuilder()
                ->columns('iSchoolId,sSchoolName')
                ->addFrom('Admin\Models\school\XhschoolInfo')
                ->where('bDelete = 0 and (iStatus = 1 OR iStatus = 2)')
                ->inWhere('iSchoolId', $schoolIds)
                ->getQuery()
                ->execute()
                ->toArray();
            $schoolList = array_column($schools, 'sSchoolName', 'iSchoolId');
        } elseif ($schoolIds) {
            $schoolList = School::getSchools();
        } else {
            $schoolList = [];
        }
        $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '提交'];
        $formButtonArr[] = ['id' => 'bt_form_close', 'text' => '取消'];
        $this->view->setVars([
            'SchoolList' => json_encode($schoolList),
            'webProblem' => $webProblem,
            'iId' => $iId,
            'FormButton' => Template::createButtonToolBar($formButtonArr),
        ]);
        return $this->view->pick('web_problem/addWebProblem');
    }

    /**
     * 保存问题
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181219
     */
    public function saveWebProblemAction()
    {
        $data = $this->request->getPost();
        if ($data['iId']) {
            if (!Power::exist('WebProblem_Edit')) {
                return $this->sendErrorResponse(403, '无网络问题编辑权限');
            }
        } else {
            if (!Power::exist('WebProblem_Add')) {
                return $this->sendErrorResponse(403, '无网络问题新增权限');
            }
        }

        // 判断学校是否为空
        if (empty($data['iSchoolId'])) {
            return $this->sendErrorResponse(400, '请选择学校');
        }

        // 判断班级是否为空
        if (empty($data['sAdClsName'])) {
            return $this->sendErrorResponse(400, '请选择班级');
        }
        // 判断学生是否为空
//        if (empty($data['iStudId'])) {
//            return $this->sendErrorResponse(400, '请选择申请的学生');
//        }

        try {
            if (!empty($data['iId'])) {
                $obj = XhwebProblem::findFirst($data['iId']);
                if ($obj->iStatus == 2) {
                    $this->sendErrorResponse(500, '问题已解决');
                }
            } else {
                $obj = new XhwebProblem();
            }
            $obj->assign($data);
            if (!$obj->save()) {
                return $data['iId'] ? $this->sendErrorResponse(500, '编辑失败') : $this->sendErrorResponse(500, '创建失败');
            }
            return $data['iId'] ? $this->sendSuccessResponse('编辑成功') : $this->sendSuccessResponse('创建成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据学校Id获取班级
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181219
     */
    public function getClassAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校id不能为空');
        }
        $classList = XhsysUser::find([
            'columns' => 'sAdClsName',
            'conditions' => 'iUserType = 1 AND bDelete = 0 AND bDisable = 0 AND sAdClsName !="" AND iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId],
            'group' => 'sAdClsName'
        ])->toArray();

        return $this->sendJsonResponse(array_column($classList, 'sAdClsName'));
    }


    /**
     * 上传图片
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181219
     */
    public function uploadImageAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendJsonResponse(['state' => '缺少文件']);
        }
        $file = $this->request->getUploadedFiles()[0];
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $fileName = $file->getName();
        $fullPath = $filePath . $fileName;
        if (!is_writable($filePath)) {
            return $this->sendJsonResponse(['state' => $filePath . '缓存无写入权限']);
        }
        $file->moveTo($fullPath);
        $result = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
        @unlink($fullPath);
        if (!$result) {
            return $this->sendJsonResponse(['state' => '上传失败']);
        }
        return $this->response->setJsonContent([
            'name' => basename($result),
            'originalName' => $fileName,
            'size' => $file->getSize(),
            'state' => 'SUCCESS',
            'type' => $file->getExtension(),
            'url' => $result
        ]);
    }

    /**
     * 删除
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * modify by zqk 20181219
     */
    public function delWebProblemAction()
    {
        if (!Power::exist('WebProblem_Del')) {
            return $this->sendErrorResponse(403, '无删除权限');
        }
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '请选择要删除的问题');
        }
        try {
            $obj = XhwebProblem::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '请选择要删除的问题');
            }
            // 最终审核状态是否为通过
//            if ($obj->iStatus == 2) {
//                return $this->sendErrorResponse(400, '该问题已解决，不能删除');
//            }
            $obj->bDelete = 1;
            $re = $obj->save();
            if (!$re) {
                return $this->sendErrorResponse(400, '删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        } catch (Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '删除失败', $e->getMessage());
        }
    }

    /**
     * 问题及回复
     *
     *
     * @return mixed
     *
     * create by zqk 20181220
     */
    public function webProblemAnswerListAction()
    {
        $iId = $this->request->getQuery('iId', 'int', 0); //问题Id
        $uid = Main::getLoginUserInfo('userId');
        if (empty($iId)) {
            return $this->sendViewError('问题Id不能为空');
        }
        $webProblem = XhwebProblem::findFirst([
            'conditions' => 'bDelete = 0 And iId = ' . $iId
        ]);

        if (empty($webProblem)) {
            return $this->sendViewError('问题不存在');
        } else {
            $webProblem = $webProblem->toArray();
            $webProblem['date'] = substr($webProblem['tCreateDate'], 5, 5);
        }

        if ($webProblem['iCreateUserId'] == $uid && Power::exist('WebProblem_Answer_Ado') && $webProblem['iStatus'] == 1) {
            $ifAdopt = 1;
        } else {
            $ifAdopt = 0;
        }

        $phql = "SELECT iId,iProblemId,sContent,bBest,iCreateUserId,tCreateDate,tLastModifyDate 
            FROM XHTrack_WebProblemAnswer where bDelete = 0 AND (iCreateUserId = $uid or bBest = 1)  AND iProblemId = $iId order by ";
        //是否有我的回答
        $myAnswer = XhwebProblemAnswer::findFirst([
            'conditions' => "bDelete = 0 AND iCreateUserId = $uid and iProblemId = $iId"
        ]);
//        if ($webProblem['iCreateUserId'] != $uid && Power::exist('WebProblem_Answer') && $webProblem['iStatus'] == 1 && empty($myAnswer)) {
        //自己的问题可自己回复
        if (Power::exist('WebProblem_Answer') && $webProblem['iStatus'] == 1 && empty($myAnswer)) {
            $ifAnswer = 1;
        } else {
            $ifAnswer = 0;
        }
        //最佳答案
//        $bestAnswer = XhwebProblemAnswer::findFirst([
//            'conditions' => "bDelete = 0 AND bBest = 1 and iProblemId = $iId"
//        ]);
//        if (!empty($myAnswer) && !empty($bestAnswer)) {
//            $myAnswerId = $myAnswer->iId;
//            $bestAnswerId = $bestAnswer->iId;
//            $phql .= "case when iId = $myAnswerId then 2 when iId = $bestAnswerId then 1 else 0 end desc,";
//        } elseif (!empty($bestAnswer) && empty($myAnswer)) {
//            $bestAnswerId = $bestAnswer->iId;
//            $phql .= "case when iId = $bestAnswerId then 1 else 0 end desc,";
//        } elseif (empty($bestAnswer) && !empty($myAnswer)) {
//            $myAnswerId = $myAnswer->iId;
//            $phql .= "case when iId = $myAnswerId then 1 else 0 end desc,";
//        }
        if (!empty($myAnswer)) {
            $myAnswerId = $myAnswer->iId;
            $phql .= "case when iId = $myAnswerId then 1 else 0 end desc,";
        }
        $phql .= "iId desc";
        $replys = $this->db->fetchAll($phql);
        foreach ($replys as $k => $v) {
            $replys[$k]['date'] = substr($v['tCreateDate'], 5, 5);
        }
        $otherReplys = XhwebProblemAnswer::find([
            'columns' => 'iId,iProblemId,sContent,bBest,iCreateUserId,tCreateDate,tLastModifyDate',
            'conditions' => "bDelete = 0 AND (iCreateUserId != $uid and bBest != 1)  AND iProblemId = $iId",
            'order' => "iId desc",
        ])->toArray();
        foreach ($otherReplys as $ke => $va) {
            $otherReplys[$ke]['date'] = substr($va['tCreateDate'], 5, 5);
        }
        Main::runUserNameById($replys, ['iCreateUserId' => 'sCreateUserName'], true);
        Main::runUserNameById($otherReplys, ['iCreateUserId' => 'sCreateUserName'], true);
        $webProbArr = [];
        $webProbArr[] = $webProblem;
        Main::runUserNameById($webProbArr, ['iCreateUserId' => 'sCreateUserName'], true);
        Main::runSchoolNameByIdStr($webProbArr, ['iSchoolId' => 'sSchoolName']);
        Assets::UEditor();
        Assets::easyUI('js/web_problem/problemReply.js');
        $this->view->setVars([
            'webProblem' => $webProbArr[0],
            'iProblemId' => $iId,
            'replys' => $replys,
            'otherReplys' => $otherReplys,
            'userId' => $uid,
            'ifAnswer' => $ifAnswer,
            'ifAdopt' => $ifAdopt,
            'ifDel' => 1,
            'ifEdit' => 1,
        ]);
        return $this->view->pick('web_problem/problemReply');
    }

    /**
     * 回答问题
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181220
     */
    public function saveAnswerAction()
    {
        if (!Power::exist('WebProblem_Answer')) {
            return $this->sendErrorResponse(403, '无回答网络问题权限');
        }
        $data = $this->request->getPost();
        $uid = Main::getLoginUserInfo('userId');
        // 判断问题Id是否为空
        if (empty($data['sContent'])) {
            return $this->sendErrorResponse(400, '回答不能为空');
        }
        try {
            if (!empty($data['iId'])) {
                $obj = XhwebProblemAnswer::findFirst($data['iId']);
                if ($obj->iCreateUserId != $uid) {
                    return $this->sendErrorResponse(500, '非回复创建者');
                }
            } else {
                //是否有我的回答
                $myAnswer = XhwebProblemAnswer::findFirst([
                    'conditions' => "bDelete = 0 AND iCreateUserId = $uid and iProblemId = {$data['iProblemId']}"
                ]);
                if (!empty($myAnswer)) {
                    return $this->sendErrorResponse(500, '您已经回答过');
                }
//                $problemInfo = XhwebProblem::findFirst([
//                    'conditions' => "bDelete = 0 and iCreateUserId = $uid and iId = {$data['iProblemId']}"
//                ]);
//                if (!empty($problemInfo)) {
//                    return $this->sendErrorResponse(500, '不能回答自己提出的问题');
//                }
                $obj = new XhwebProblemAnswer();
            }
            $obj->assign($data);
            if (!$obj->save()) {
                return $data['iId'] ? $this->sendErrorResponse(500, '编辑失败') : $this->sendErrorResponse(500, '创建失败');
            }
            return $data['iId'] ? $this->sendSuccessResponse('编辑成功') : $this->sendSuccessResponse('创建成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除答案
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180716
     */
    public function delAnswerByIdAction()
    {
//        if (!Power::exist('WebProblem_Answer_Del')) {
//            return $this->sendErrorResponse(500, '权限不足', '无删除权限');
//        }
        $uid = Main::getLoginUserInfo('userId');
        $iId = $this->request->getPost('iId', 'int');
        try {
            $obj = XhwebProblemAnswer::findFirst([
                'conditions' => "bDelete = 0 AND iId = $iId"
            ]);
            if (!$obj) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            if ($obj->bBest == 1) {
                return $this->sendErrorResponse(500, '最优回答不能删除');
            }
            if ($obj->iCreateUserId != $uid) {
                return $this->sendErrorResponse(500, '非回复创建者');
            }
            $obj->bDelete = 1;
            $re = $obj->save();
            if (!$re) {
                return $this->sendErrorResponse('500', '删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 采纳答案
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181220
     */
    public function adoptAnswerByIdAction()
    {
        if (!Power::exist('WebProblem_Answer_Ado')) {
            return $this->sendErrorResponse(403, '无回答网络问题权限');
        }
        $iId = $this->request->getPost('iId');
        $uid = Main::getLoginUserInfo('userId');
        if (empty($iId)) {
            return $this->sendErrorResponse(400, '请选择要采纳的答案');
        }
        try {
            $this->db->begin();
            $obj = XhwebProblemAnswer::findFirst($iId);
            if (empty($obj)) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '要采纳的答案不存在');
            }
            $obj->bBest = 1;
            $re = $obj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }
            $problemId = $obj->iProblemId;
            $problemObj = XhwebProblem::findFirst([
                'conditions' => "bDelete = 0 AND iId = $problemId",
            ]);
            if (empty($problemObj)) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '问题不存在');
            }
            if ($problemObj->iCreateUserId != $uid) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '非问题所有者');
            }
            if ($problemObj->iStatus == 2) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '问题已解决');
            }
            $problemObj->iStatus = 2;
            $res = $problemObj->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }

    }

    /**
     * 根据省份获取city
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * @throws \Exception
     *
     * create by zqk 20181229
     */
    public function getCityDataByProvIdAction()
    {
        $provId = $this->request->getQuery('provId');
        $data[] = [
            'value' => '',
            'text' => '--市--',
        ];
        if (empty($provId)) {
            return $this->sendJsonResponse($data);
        }
        $areaObj = new Area((int)$provId);
        $allCity = $areaObj->getCity();
        foreach ($allCity as $key => $value) {
            $data[] = [
                'value' => $key,
                'text' => $value,
            ];
        }
        return json_encode($data);
    }

    /**
     * 根据城市获取区
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * @throws \Lybc\PhpGB2260\InvalidCodeException
     *
     * create by zqk 20181229
     */
    public function getZoneDataByCityIdAction()
    {
        $cityId = $this->request->getQuery('cityId');
        $data[] = [
            'value' => '',
            'text' => '--区--',
        ];
        if (empty($cityId)) {
            return $this->sendJsonResponse($data);
        }
        $areaObj = new Area((int)$cityId);
        $allZone = $areaObj->getDistrict();
        foreach ($allZone as $key => $value) {
            $data[] = [
                'value' => $key,
                'text' => $value,
            ];
        }
        return json_encode($data);
    }

    /**
     * 获取地域信息
     *
     * @return mixed
     *
     * create by zqk 20181229
     */
    public function getDepDataAction(){
        try {
            $data  = Hrm::getDepArray('XHYYB', 2, true);
            Tool::replaceKey($data, ['child' => 'children']);
            array_unshift($data, ['id' => '', 'text' => '--选择区域--', 'children' => []]);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

}

